//
//  AppDelegate.m
//  WCN
//
//  Created by 杨鑫 on 15/5/29.
//  Copyright (c) 2015年 ShanghaiCize Trade And Business Co., Ltd. All rights reserved.
//

extern"C"{
    size_t fwrite$UNIX2003(const void *a, size_t b, size_t c, FILE *d )
    {
        return fwrite(a, b, c, d);
    }
    char* strerror$UNIX2003( int errnum )
    {
        return strerror(errnum);
    }
}
#import "WCNAppDelegate.h"
//vc
#import "WCNNavigationController.h"
#import "WCNTabBarVC.h"
#import "WCNGuideVC.h"
#import "WCNLoginVC.h"
//
#import "WCNetworkAccessManager.h"
#import "WCImageManager.h"
#import "WCCoreDataStore.h"
#import "WCNConstantsCDStore.h"
#import "WCDefaultManager.h"
//
#import "Constants.h"
#import "Macros.h"
#import "WCNSettingItemController.h"
//#import "ChatManager.h"

//#import "AppDelegate+EaseMob.h"
//#import "AppDelegate+Parse.h"
#import "WSJVersionCheck.h"
#import "WCAppDlegate+baidu.h"
#import "BPush.h"
#import "JCAlertView.h"
#import "WCBPushToolByWsj.h"
#import "cwqMessageTypesVC.h"
//#import "EMCDDeviceManager.h"
#import "AppDelegate+WeixinConfig.h"
//#import "NdUncaughtExceptionHandler.h"
#import "AppDelegate+ZhuMu.h"
#import <ZhumuSDK/ZhumuSDK.h>
#import "WSJBundleVersionManger.h"
#import "WSJObserveNewChatTool.h"
#import "XHMessage.h"
#import "WSJConversion.h"
#import "CWQXHMessage+CoreDataProperties.h"
#import "UMMobClick/MobClick.h"



@interface WCNAppDelegate ()

@end

@implementation WCNAppDelegate




- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    // Override point for customization after application launch.
 
  

    
    [WCNetworkAccessManager sharedMg];
    [WCImageManager sharedMg];
    [WCCoreDataStore shareStore];
    [WCDefaultManager shareMg];
//    [WSJObserveNewChatTool chatMessageWithApplication:application didFinishLaunchingWithOptions:launchOptions];
//    [WSJObserveNewChatTool sharedObserveTool];
    
  

    
    //初始化环信
    //    [self setUpEasob:application WithOptions:launchOptions];
    //初始化百度推送
    [self baiduApplication:application didFinishLaunchingWithOptions:launchOptions];
    
    [self wexinApplication:application didFinishLaunchingWithOptions:launchOptions];
    
    
     //初始化友盟 正式 578da41967e58e4b4d003511
   
    UMConfigInstance.appKey = @"578da41967e58e4b4d003511";
    [MobClick startWithConfigure:UMConfigInstance];//配置以上参数后调用此方法初始化SDK！
    
    //启动的时候(每次启动 算登陆一次)
    [MobClick event:@"Login"];
    
    //    [[ChatManager sharedChatManager] autoRegistWithMobile:@"nurse_13052097297"];
    self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
    self.window.backgroundColor = [UIColor whiteColor];
    [WSJBundleVersionManger manager].setWindow(self.window).isNeedNewFeaturePage =NO;
    
    [self finishLaunchingWithOptions:launchOptions];

    return YES;
}
#pragma mark - Orientation  单个页面横屏

- (UIInterfaceOrientationMask)application:(UIApplication *)application supportedInterfaceOrientationsForWindow:(UIWindow *)window
{
   
    WCNNavigationController *nav = (WCNNavigationController *)self.window.rootViewController;

//    if ([nav.visibleViewController isKindOfClass:[WCNCreateMeetingVC class]])
//    {
//        WCNCreateMeetingVC *vc = (WCNCreateMeetingVC *) nav.visibleViewController;
//        
        if (self.isMeetingNow)
        {
            return UIInterfaceOrientationMaskAll;
        }
        else return UIInterfaceOrientationMaskPortrait;
//    }
//    else return UIInterfaceOrientationMaskPortrait;
}

// 此方法是 用户点击了通知，应用在前台 或者开启后台并且应用在后台 时调起
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler
{
    
    //    推送来来自百度
    if (userInfo[@"aps"] &&!userInfo[@"m"]) {
        NSInteger num =[userInfo[@"aps"][@"badge"] integerValue];
        if (num && num>0) {
            [WCBPushToolByWsj saveNewBadge:num];
        }
        
        if (application.applicationState == UIApplicationStateActive || application.applicationState == UIApplicationStateBackground) {
            UIApplicationState state = [[UIApplication sharedApplication] applicationState];
            switch (state) {
                case UIApplicationStateActive:
                    [self playSoundAndVibration];
                    [JCAlertView showTwoButtonsWithTitle:@"通知" Message:userInfo[@"aps"][@"alert"] ButtonType:JCAlertViewButtonTypeCancel ButtonTitle:@"忽略" Click:^{
                        
                    } ButtonType:JCAlertViewButtonTypeDefault ButtonTitle:@"前往查看" Click:^{
                        
                        WCNNavigationController *nav =[[UIApplication sharedApplication].delegate window].rootViewController;
                        [nav pushViewController:[cwqMessageTypesVC new] animated:YES];
                        //                        WCMainNewViewController *tbc =[[UIApplication sharedApplication].delegate window].rootViewController;
                        //                        tbc.selectedIndex = 3;
                        //
                        //                        [tbc.selectedViewController pushViewController:[cwqMessageTypesVC new] animated:YES];
                        
                    }];
                    
                    break;
                case UIApplicationStateInactive:
                    [JCAlertView showTwoButtonsWithTitle:@"通知" Message:userInfo[@"aps"] ButtonType:JCAlertViewButtonTypeCancel ButtonTitle:@"忽略" Click:^{
                        
                    } ButtonType:JCAlertViewButtonTypeDefault ButtonTitle:@"前往查看" Click:^{
                        
                    }];
                    
                    [self playSoundAndVibration];
                    break;
                case UIApplicationStateBackground:
                    
                    
                    
                    break;
                default:
                    
                    break;
            }
            
            
        }else{
            
            //            WCMainNewViewController *tbc =[[UIApplication sharedApplication].delegate window].rootViewController;
            //            tbc.selectedIndex = 3;
            //            [tbc.selectedViewController.navigationController pushViewController:[cwqMessageTypesVC new] animated:YES];
            
            
        }
        
        
    }
    //    completionHandler(UIBackgroundFetchResultNewData);
    //    // 打印到日志 textView 中
    //    NSLog(@"********** iOS7.0之后 background **********");
    //    // 应用在前台 或者后台开启状态下，不跳转页面，让用户选择。
    //    if (application.applicationState == UIApplicationStateActive || application.applicationState == UIApplicationStateBackground) {
    
    //        [BPush showLocalNotificationAtFront:userInfo identifierKey:nil];
    //        [self testLocalNotifi];
    ////        NSLog(@"acitve or background");
    ////        UIAlertView *alertView =[[UIAlertView alloc]initWithTitle:@"收到一条消息" message:userInfo[@"aps"][@"alert"] delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
    ////        [alertView show];
    //        [WSJLocalNotificationTool registerLocalNotification:0];
    //    }
    //    else//杀死状态下，直接跳转到跳转页面。
    //    {
    //        WCMainNewViewController *tbc = [[UIApplication sharedApplication].delegate window].rootViewController;
    //        tbc.selectedIndex =3;
    //        [tbc.selectedViewController pushViewController:[cwqMessageTypesVC new] animated:YES];
    //    }
    //
    
    
}
- (void)playSoundAndVibration{
    
    
    // 收到消息时，播放音频
    //    [[EMCDDeviceManager sharedInstance] playNewMessageSound];
    //    // 收到消息时，震动
    //    [[EMCDDeviceManager sharedInstance] playVibration];
}

- (void)applicationWillResignActive:(UIApplication *)application {
        [[ZhumuSDK sharedSDK] appWillResignActive];
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}

- (void)applicationDidEnterBackground:(UIApplication *)application {
    
    //    [WCNAppDelegate resetIconBadageNumber];
    BOOL save = [[WCCoreDataStore shareStore] saveData];
    if (save) {
        Log(@"WCCoreDataStore保存成功!");
    } else {
        Log(@"WCCoreDataStore保存失败!");
    }
    
    save = [[WCNConstantsCDStore shareStore] saveData];
    if (save) {
        Log(@"WCNConstantsCDStore保存成功!");
    } else {
        Log(@"WCNConstantsCDStore保存失败!");
    }
}

- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
    //    [[EaseMob sharedInstance] applicationWillEnterForeground:application];
}

- (void)applicationDidBecomeActive:(UIApplication *)application {
    [[ZhumuSDK sharedSDK] appDidBecomeActive];
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
    //     [[EaseMob sharedInstance] applicationDidEnterBackground:application];
}

- (void)applicationWillTerminate:(UIApplication *)application {
    
    
}

- (void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification
{
    NSDictionary *dict = notification.userInfo;
    if (dict[@"content"]) {
        //本地通知来自前微信聊天的本地推送
        
        cwqMessageTypesVC *vc =[cwqMessageTypesVC new];
        WCNNavigationController *nav =[[UIApplication sharedApplication].delegate window].rootViewController;
        [nav pushViewController:vc animated:YES];
        
    }
    
    [application cancelLocalNotification:notification];
}
@end
